package com.example.stockholdtrack.data

import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import java.io.IOException
import java.util.concurrent.TimeUnit

class StockApiService {
    private val client = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .build()
    
    data class StockPriceData(
        val currentPrice: Double,
        val stockCode: String
    )
    
    suspend fun getStockPrice(stockCode: String): StockPriceData? {
        return withContext(Dispatchers.IO) {
            try {
                // 根据股票代码确定市场前缀
                val secid = when {
                    stockCode.startsWith("6") -> "1.$stockCode" // 沪市A股
                    stockCode.startsWith("0") || stockCode.startsWith("3") -> "0.$stockCode" // 深市A股
                    else -> "0.$stockCode" // 默认深市
                }
                
                val url = "https://push2.eastmoney.com/api/qt/stock/get?secid=$secid&fields=f43,f57"
                
                println("DEBUG: StockApiService.getStockPrice - 请求URL: $url")
                
                val request = Request.Builder()
                    .url(url)
                    .build()
                
                val response = client.newCall(request).execute()
                
                if (response.isSuccessful) {
                    val jsonString = response.body?.string()
                    if (jsonString != null) {
                        println("DEBUG: StockApiService.getStockPrice - 响应数据: $jsonString")
                        
                        val stockData = parseStockData(jsonString)
                        println("DEBUG: StockApiService.getStockPrice - 解析结果: $stockData")
                        stockData
                    } else {
                        println("DEBUG: StockApiService.getStockPrice - 响应体为空")
                        null
                    }
                } else {
                    println("DEBUG: StockApiService.getStockPrice - 请求失败: ${response.code}")
                    null
                }
            } catch (e: IOException) {
                println("DEBUG: StockApiService.getStockPrice - 网络错误: ${e.message}")
                null
            } catch (e: Exception) {
                println("DEBUG: StockApiService.getStockPrice - 解析错误: ${e.message}")
                null
            }
        }
    }
    
    private fun parseStockData(jsonString: String?): StockPriceData? {
        if (jsonString == null) {
            println("DEBUG: StockApiService.parseStockData - JSON字符串为空")
            return null
        }
        
        return try {
            val json = JSONObject(jsonString)
            val data = json.getJSONObject("data")
            
            // 检查返回码
            val rc = json.optInt("rc", -1)
            if (rc != 0) {
                println("DEBUG: StockApiService.parseStockData - API返回错误码: $rc")
                return null
            }
            
            StockPriceData(
                currentPrice = data.getInt("f43") / 100.0, // 当前价格（分转元）
                stockCode = data.getString("f57")
            )
        } catch (e: Exception) {
            println("DEBUG: StockApiService.parseStockData - 解析异常: ${e.message}")
            null
        }
    }
} 